package com.module04.work.demo04;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {

    public static User getUser(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String userName = sc.next();
        System.out.println("请输入密码：");
        String password = sc.next();
        sc.close();
        return new User(userName,password);
    }

    public static void main(String[] args) {

        Socket s = null;
        ObjectOutputStream oos = null;////获取输出流
        ObjectInputStream ois = null;////获取输入流
        UserMessage tum = null;

        try {
            // 1.创建Socket类型的对象并提供服务器的主机名和端口号
            s = new Socket("127.0.0.1", 8888);
            System.out.println("服务器连接成功！");
            //2.使用输入输出(对象)流进行通信
            //实现客户端发送对象内容，调用getUser方法手动输入用户名密码
            tum = new UserMessage("check",Client.getUser());
            oos = new ObjectOutputStream(s.getOutputStream());
            oos.writeObject(tum);

            //接受服务器回发的消息并判断登录是否成功
            ois = new ObjectInputStream(s.getInputStream());
            UserMessage uMsg = (UserMessage) ois.readObject();
            if (uMsg.getType().equals("success")){
                System.out.println("登陆成功！");
            }else {
                System.out.println("登录失败！");
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //3.关闭Socket并释放有关的资源
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
